package algorithm.queue;

/**
 * @author bingo
 * @Description 循环队列
 * @Date 2018/6/3
 */
public class LoopQueue<E> implements Queue<E> {

    private E[] data;

    private int front;

    private int tail;

    private int size;

    public LoopQueue(int capacity) {
        data = (E[])new Object[capacity+1];
        front=0;
        tail=0;
    }

    @Override
    public void enqueue(E e) {
        if((tail+1)%data.length==front){
            System.out.println("tail："+tail);
            resize(getCapacity()*2);
        }
        data[tail]=e;
        tail  = (tail+1) % data.length;
        size++;

    }
   /**
    * 对数组进行扩容
    * */
    private void resize(int newCapacity) {
        E[] newData =(E[])new Object[newCapacity+1];
        for(int i=0;i<size;i++){
          newData[i] = data[(i+front)%data.length];
        }
        data = newData;
        front = 0;
        tail = size;

    }

    @Override
    public E dequeue() {
        E ret = data[front];
        data[front] = null;
        front = (front+1) % data.length;
        size--;
        return ret;
    }

    @Override
    public E front() {
        return null;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return front ==tail;
    }

    public int getCapacity(){
        return data.length-1;
    }

    public String toString(){

        StringBuilder result = new StringBuilder();
        result.append(String.format("Quenue：size=%d,capacity=%d;",size,getCapacity()));
        result.append("front[");
        for(int i=front;i!=tail;i=(i+1)%data.length){
            result.append(data[i]);
            if((i+1)%data.length!=tail){
                result.append(',');
            }
        }
        result.append("]");
        return  result.toString();

    }

    public static void main(String[] args) {
       LoopQueue loopQueue = new LoopQueue(5);
        loopQueue.enqueue(1);
        loopQueue.enqueue(2);
        loopQueue.enqueue(3);
        loopQueue.enqueue(4);
        loopQueue.enqueue(5);
        System.out.println(loopQueue.toString());
        loopQueue.dequeue();
        System.out.println(loopQueue.toString());
        loopQueue.enqueue(0);
        loopQueue.enqueue(5);
        System.out.println(loopQueue.toString());




    }
}
